package service

import (
	"context"
	"rpc-server/basic/config"
	__ "rpc-server/basic/proto"
	"rpc-server/handler/model"
	"rpc-server/pkg"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) MobileCaptchaLogin(_ context.Context, in *__.MobileCaptchaLoginReq) (*__.MobileCaptchaLoginResp, error) {
	user := &model.Users{
		PhoneNumber: in.PhoneNumber,
	}
	// 1. 校验参数
	if in.PhoneNumber == "" || in.Captcha == "" {
		return &__.MobileCaptchaLoginResp{
			Code: 400,
			Msg:  "参数错误",
		}, nil
	}
	// 2. 校验验证码
	if in.Captcha != "1234" {
		return &__.MobileCaptchaLoginResp{
			Code: 400,
			Msg:  "验证码错误",
		}, nil
	}

	pkg.ShortSDK(user.PhoneNumber, in.Captcha)
	return &__.MobileCaptchaLoginResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}

func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	user := &model.Users{
		PhoneNumber:  in.PhoneNumber,
		PasswordHash: in.Password,
	}
	if in.PhoneNumber != user.PhoneNumber && in.Password != user.PasswordHash {
		return &__.RegisterResp{
			Code: 400,
			Msg:  "参数错误",
		}, nil
	}
	if err := config.DB.Create(&user).Error; err != nil {
		return &__.RegisterResp{
			Code: 500,
			Msg:  "注册失败",
		}, nil
	}

	return &__.RegisterResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}
func (s *Server) VideoReview(_ context.Context, in *__.VideoReviewReq) (*__.VideoReviewResp, error) {
	video := &model.Videos{}
	if err := config.DB.Where("id = ?", in.VideoId).Find(&video).Error; err != nil {
		return &__.VideoReviewResp{
			Code: 400,
			Msg:  "视频不存在",
		}, nil
	}
	if err := config.DB.Create(&video); err != nil {
		return &__.VideoReviewResp{
			Code: 500,
			Msg:  "视频审核失败",
		}, nil
	}
	return &__.VideoReviewResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}
func (s *Server) ListVideoReview(_ context.Context, in *__.ListVideoReviewReq) (*__.ListVideoReviewResp, error) {
	video := &model.Videos{}
	if err := config.DB.Where("id = ?", in.Id).Find(&video).Error; err != nil {
		return &__.ListVideoReviewResp{
			Code: 400,
			Msg:  "视频不存在",
		}, nil
	}

	return &__.ListVideoReviewResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}
